#include "GY_ListenerHelper.h"
#include <QDebug>

QMap<QString, QList<Hander>> GY_ListenerHelper::m_listenerMap;

GY_ListenerHelper::GY_ListenerHelper()
{

}

/**
 * @brief addListener 添加监听对象
 * @param eventName 事件名称
 * @param receiver 对象
 * @param methodName 方法名称
 */
void GY_ListenerHelper::addListener(const QString &eventName, QObject *pReceiver, const char *pMethodName)
{
    if(pReceiver==nullptr)
    {
        qDebug()<<"GY_ListenerHelper::addListener: receiver==nullptr";
        return;
    }
    QList<Hander> &handerList = m_listenerMap[eventName];
    for(int i = 0; i < handerList.length(); i++)
    {
        const Hander &obj = handerList.at(i);
        if(obj.first.data() == pReceiver){
            qDebug()<< QString("GY_ListenerHelper::addListener:%1").arg(pReceiver->objectName());
            return;
        }
    }

    Hander hander;
    hander.first = pReceiver;
    hander.second = pMethodName;
    handerList<< hander;
}

/**
 * @brief removeListener 移除监听对象
 * @param receiver 对象
 */
void GY_ListenerHelper::removeListener(QObject *pReceiver)
{
    QMap<QString,QList<Hander>>::Iterator iter = m_listenerMap.begin();
    while(iter !=m_listenerMap.end())
    {
        QList<Hander> &handerList = iter.value();
        for(int i=0;i<handerList.length();++i)
        {
            const Hander &hander = handerList.at(i);
            if(hander.first==pReceiver)
            {
                handerList.removeAt(i);
                break;
            }
        }
        if(handerList.length()==0)
        {
            iter = m_listenerMap.erase(iter);
        }
        else {
            ++iter;
        }
    }
}

/**
 * @brief emitEvent 事件响应
 * @param eventName 事件名称
 * @param data 数据
 */
void GY_ListenerHelper::emitEvent(const QString &eventName, const QVariant &data)
{
    if(m_listenerMap.contains(eventName)==false)
    {
        qDebug()<< QString("GY_ListenerHelper::emitEvent: there is no such eventName: %1").arg(eventName);
        return;
    }
    const QList<Hander> &handerList = m_listenerMap[eventName];
    for(int i=0; i<handerList.length();i++)
    {
        const Hander &hander = handerList.at(i);
        if(hander.first.isNull())
        {
            continue;
        }
        QObject* pReciver = hander.first;
        const char* pMethodName = hander.second;
        bool ok = QMetaObject::invokeMethod(pReciver,pMethodName,Qt::AutoConnection,QGenericReturnArgument(),Q_ARG(QVariant,data));
        if(!ok)
        {
            qDebug()<< QString("GY_ListenerHelper::emitEvent: %1 Description Failed to process Event! %2").arg(pReciver->objectName(), pMethodName);
        }
    }
}
